public class BiarrySearchTree {

    public class Node{
        public Node left;
        public Node right;
        public int val;

        public Node(int val) {
            this.val = val;
        }
    }

    public static Node root;

    public void insert(int val){
        if(root == null){
            root = new Node(val);
            return ;
        }

        Node parent = root;
        Node cur = root;
        while (cur != null){
            parent = cur;
            if(cur.val > val){
                cur = cur.left;
            }else{
                cur = cur.right;
            }
        }
        if(parent.val > val){
            parent.left = new Node(val);
        }else {
            parent.right = new Node(val);
        }
    }

    public boolean search(int val){
        if(root == null){
            return false;
        }

        Node cur = root;
        while (cur != null){
            if(cur.val > val){
                cur = cur.left;
            }else if(cur.val == val){
                return true;
            }else {
                cur = cur.right;
            }
        }
        return false;
    }

    public void remove(int val){
        if(root == null){
            return ;
        }

        Node parent = root;
        Node cur = root;
        while (cur != null) {
            parent = cur;
            if (cur.val > val) {
                cur = cur.left;
            } else if(cur.val < val){
                cur = cur.right;
            }else {
                break;
            }
        }
        removeChild(parent,cur);
        
    }

    private void removeChild(Node parent, Node cur) {
        // 当cur没有左子树时
        if (cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(parent.right == cur){
                parent.right = cur.right;
            } else{
                parent.left = cur.right;
            }
        }
        // 当cur没有右子树时
        else if (cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(parent.right == cur){
                parent.right = cur.left;
            } else{
                parent.left = cur.left;
            }
        }else {
            Node target = cur.right;
            Node targetParent = cur;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }

            cur.val = target.val;

            if(target == targetParent.right){
                targetParent.right = target.right;
            }else {
                targetParent.left = target.right;
            }
        }








    }


}
